<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规格类别" prop="type">
        <el-input v-model="queryParams.type" placeholder="请输入规格类别" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['shopping:CommodityType:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['shopping:CommodityType:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['shopping:CommodityType:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['shopping:CommodityType:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="CommodityTypeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <!-- <el-table-column label="商品ID" align="center" prop="commodityId" /> -->
      <el-table-column label="商品" align="center" prop="commodityName" />
      <el-table-column label="规格类别" align="center" prop="type" />
      <el-table-column label="商品图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="商品库存" align="center" prop="inventory" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['shopping:CommodityType:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['shopping:CommodityType:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品ID" prop="commodityId">
          <el-input v-model="form.commodityId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="规格列表">
          <el-button type="primary" @click="addSpecification">添加规格</el-button>
          <div v-for="(spec, index) in form.specifications" :key="index">
            <el-form-item :prop="'specifications.' + index + '.type'">
              <el-input v-model="form.specifications[index].type" placeholder="请输入规格类别" />
            </el-form-item>
            <el-form-item :prop="'specifications.' + index + '.image'">
              <image-upload v-model="form.specifications[index].image" />
            </el-form-item>
            <el-form-item :prop="'specifications.' + index + '.inventory'">
              <el-input v-model="form.specifications[index].inventory" placeholder="请输入商品库存" />
            </el-form-item>
            <el-button type="danger" @click="removeSpecification(index)">删除规格</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    listCommodityType,
    getCommodityType,
    delCommodityType,
    addCommodityType,
    updateCommodityType,
    addType,
    clearCommodityType
  } from "@/api/shopping/CommodityType";

  export default {
    name: "CommodityType",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品类型管理表格数据
        CommodityTypeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          type: null,
        },
        open: false,
        selectedProduct: null,
        // 表单参数
        form: {
          id:null,
          commodityId: null,
          specifications: [{
            type: '',
            image: '',
            inventory: ''
          }]
        },
        // 表单校验
        rules: {}
      };
    },
    created() {
      this.getList();
    },
    methods: {
      addSpecification() {
        this.form.specifications.push({
          type: '',
          image: '',
          inventory: ''
        });
      },
      removeSpecification(index) {
        if (this.form.specifications.length > 1) {
          this.form.specifications.splice(index, 1);
        }
      },

      /** 查询商品类型管理列表 */
      getList() {
        this.loading = true;
        listCommodityType(this.queryParams).then(response => {
          this.CommodityTypeList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();

      },
      // 表单重置
      reset() {
        this.selectedProduct = null;
        this.form = {
          id: null,
          commodityId: null,
          specifications: [{
            type: null,
            image: null,
            inventory: null
          }],
          del: 0
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加商品类型管理";
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        console.log(id)
        getCommodityType(id).then(response => {
          const data = response.data;
          this.form = {
            id:data.id,
            commodityId: data.commodityId,
            specifications: [{
              type: data.type,
              image: data.image,
              inventory: data.inventory
            }],
          };
          console.log(this.form.specifications)
          console.log(response.data)
          this.$nextTick(() => {
            this.open = true;
            this.title = "修改商品类型管理";
          });
        });
      },
      submitForm() {
        this.dataProcessing = true; // 设置标志变量
        console.log("当前表单 ID:", this.form.id);
        console.log("表单数据:", this.form);
        // 验证表单
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id == null) {
              // 新增操作
              const requests = this.form.specifications.map(spec => {
                const data = {
                  commodityId: this.form.commodityId,
                  type: spec.type,
                  image: spec.image,
                  inventory: spec.inventory
                };
                console.log("新增请求数据:", data); // 打印请求数据
                return addCommodityType(data); // 调用新增 API
              });

              Promise.all(requests).then(responses => {
                console.log("新增API 响应:", responses); // 打印响应信息
                const success = responses.every(resp => resp.code === 200);
                if (success) {
                  this.$message.success("批量新增成功!");
                  this.open = false;
                  this.getList();
                } else {
                  this.$message.error("批量新增有失败!");
                }
              }).catch(error => {
                this.$message.error("批量新增出错: " + error.message);
                console.log("请求错误:", error); // 打印请求错误信息
              }).finally(() => {
                this.dataProcessing = false; // 确保在操作完成后重置标志变量
              });

            } else {
              // 修改操作
              // 清空旧数据
              clearCommodityType(this.form.id).then(resp => {
                console.log("清空响应数据:", resp); // 打印清空响应数据
                  if (resp.code == 200) {
                    // 清空成功
                    const requestData = {
                      id: this.form.id,
                      commodityId: this.form.commodityId,
                      type: this.form.specifications[0].type,
                      image: this.form.specifications[0].image,
                      inventory: this.form.specifications[0].inventory
                    };
                    console.log("修改请求数据:", requestData); // 打印请求数据
                    return updateCommodityType(requestData); // 调用修改 API
                  } else {
                    return Promise.reject(new Error('清空数据失败'));
                  }
                })
                .then(updateResponse => {
                  if (updateResponse.code == 200) {
                    this.$message.success('修改成功!');
                    this.open = false;
                    this.getList();
                  } else {
                    this.$message.error('修改失败!');
                  }
                })
                .catch(error => {
                  this.$message.error('操作出错: ' + error.message);
                  console.log("请求错误:", error); // 打印请求错误信息
                })
                .finally(() => {
                  this.dataProcessing = false; // 确保在操作完成后重置标志变量
                });
            }
          } else {
            this.dataProcessing = false; // 确保在操作完成后重置标志变量
          }
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除商品类型管理编号为"' + ids + '"的数据项？').then(function() {
          return delCommodityType(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('shopping/CommodityType/export', {
          ...this.queryParams
        }, `CommodityType_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
